package com.dy.vueadminservice.handler;

import com.dy.vueadminservice.result.RespEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * APP环境下认证失败处理器
 *
 * @author huangdeyao
 */
@Component("authenticationFailureHandler")
public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException {
        logger.info("登录失败");
        httpServletResponse.setStatus(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value());
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //将authentication这个对象转成json格式的字符串
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new RespEntity(-1, exception.getMessage(), null)));
    }
}
